/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.panpf.sketch.sample.widget.fraction;

import cn.bingoogolapple.refreshlayout.BgarefreshLayout;
import cn.bingoogolapple.refreshlayout.BgaStickinessRefreshViewHolder;
import com.google.gson.Gson;

import me.panpf.sketch.sample.util.ScrollingPauseLoadManager;
import me.panpf.sketch.util.TextUtils;
import ohos.agp.components.*;

import me.panpf.sketch.sample.ResourceTable;
import me.panpf.sketch.sample.item.BaiduStaggeredImageItem;
import me.panpf.sketch.sample.net.HttpCallBackListener;
import me.panpf.sketch.sample.net.NetServices;
import me.panpf.sketch.sample.bean.BaiduImageSearchResult;

import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

/**
 * BaiduGifFraction
 */
public class BaiduGifFraction extends Fraction implements BgarefreshLayout.BgarefreshLayoutDelegate {
    private int pageIndex = 1;

    /**
     * PAGE_SIZE
     */
    private static final int PAGE_SIZE = 25;

    private BgarefreshLayout bgaRefreshLayout;
    private ListContainer mListView;
    private BaiduStaggeredImageItem mListAdapter;
    private List<String> imageUrlList = new ArrayList<>();
    private Text mTextTip;
    private DependentLayout mLayoutTip;
    private Button btnRetry;

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        Component component = scatter.parse(ResourceTable.Layout_baidugif_fraction, container, false);
        return component;
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);

        bgaRefreshLayout = (BgarefreshLayout) getComponent().findComponentById(ResourceTable.Id_bgaRefreshLayout);
        bgaRefreshLayout.setDelegate(this);
        BgaStickinessRefreshViewHolder srfViewHolder = new BgaStickinessRefreshViewHolder(getComponent().getContext(), true);
        srfViewHolder.setRefreshViewBackgroundColorRes(ResourceTable.Color_color_ability_bg);
        srfViewHolder.setLoadMoreBackgroundColorRes(ResourceTable.Color_color_ability_bg);
        srfViewHolder.setLoaderTextColor(ResourceTable.Color_text_normal);
        bgaRefreshLayout.setIsShowLoadingMoreView(false);
        bgaRefreshLayout.setPullDownRefreshEnable(true);
        bgaRefreshLayout.setRefreshViewHolder(srfViewHolder);

        mListView = (ListContainer) getComponent().findComponentById(ResourceTable.Id_mList);
        mListAdapter = new BaiduStaggeredImageItem(this, imageUrlList);
        mListView.addScrolledListener(new ScrollingPauseLoadManager(getFractionAbility(), mListAdapter));
        mListView.setItemProvider(mListAdapter);
        mListView.setLongClickable(false);

        mLayoutTip = (DependentLayout) getComponent().findComponentById(ResourceTable.Id_layout_tip);
        mTextTip = (Text) getComponent().findComponentById(ResourceTable.Id_text_tip);
        btnRetry = (Button) getComponent().findComponentById(ResourceTable.Id_btn_retry);
        btnRetry.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                bgaRefreshLayout.beginRefreshing();
                mLayoutTip.setVisibility(Component.HIDE);
            }
        });

        bgaRefreshLayout.beginRefreshing();
    }

    private void onLoadMore() {
        this.loadData(this.pageIndex + 1);
    }

    private void loadData(int pageIndex) {
        this.pageIndex = pageIndex;
        int pageStart = (pageIndex - 1) * PAGE_SIZE;
        if (pageIndex <= 1) {
            imageUrlList.clear();
        }
        String url = null;
        try {
            url = getFractionAbility().getResourceManager().getElement(ResourceTable.String_baiduUrl).getString();
        } catch (IOException | NotExistException | WrongTypeException ex) {
            ex.printStackTrace();
        }
        if (!TextUtils.isEmpty(url)) {
            getNetData(url, pageStart);
        }
    }

    private void getNetData(String url, int pageStart) {
        NetServices.searchBaiduImage(url, "GIF", "GIF", pageStart, PAGE_SIZE, new HttpCallBackListener() {
            @Override
            public void onResponse(String rsp) {
                try {
                    filterData(rsp);
                    if (getFractionAbility() == null) {
                        return;
                    }
                    getComponent().getContext().getUITaskDispatcher().asyncDispatch(() -> {
                        mListAdapter.notifyDataChanged();
                        if (imageUrlList.isEmpty()) {
                            mTextTip.setText("No photos");
                            btnRetry.setVisibility(Component.INVISIBLE);
                            mLayoutTip.setVisibility(Component.VISIBLE);
                        } else {
                            btnRetry.setVisibility(Component.VISIBLE);
                            mLayoutTip.setVisibility(Component.HIDE);
                        }
                        bgaRefreshLayout.endRefreshing();
                        bgaRefreshLayout.endLoadingMore();
                    });
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

            @Override
            public void onFailure(Exception ex) {
                if (getFractionAbility() == null) {
                    return;
                }
                if (pageIndex <= 1) {
                    getComponent().getContext().getUITaskDispatcher().asyncDispatch(() -> {
                        mLayoutTip.setVisibility(Component.VISIBLE);
                        if (ex instanceof SocketTimeoutException) {
                            mTextTip.setText("网络连接超时");
                        } else {
                            mTextTip.setText("没有网络连接");
                        }
                        mListAdapter.notifyDataChanged();
                        bgaRefreshLayout.endRefreshing();
                        bgaRefreshLayout.endLoadingMore();
                    });
                }
            }
        });
    }

    private void filterData(String rsp) {
        Gson gson = new Gson();
        BaiduImageSearchResult searchResult = gson.fromJson(rsp, BaiduImageSearchResult.class);
        List<BaiduImageSearchResult.BaiduImage> imageList = searchResult.getImageList();
        if (imageList != null && !imageList.isEmpty()) {
            for (int i = 0; i < imageList.size(); i++) {
                String url = imageList.get(i).getUrl();
                if (url != null && !url.isEmpty()) {
                    imageUrlList.add(url);
                }
            }
        }
    }


    @Override
    public void onBgarefreshLayoutBeginRefreshing(BgarefreshLayout bgarefreshLayout) {
        loadData(1);
    }

    @Override
    public boolean onBgarefreshLayoutBeginLoadingMore(BgarefreshLayout bgarefreshLayout) {
        // onLoadMore();
        return false;
    }
}
